<?php

namespace common\jobs;

use Yii;
use yii\helpers\ArrayHelper;
use JPush\Client;
use yii\console\Exception;

/**
 * JPush推送消息
 * Class JPushJob.
 */
class JPushJob extends \yii\base\BaseObject implements \yii\queue\JobInterface {

    public $title = null;
    public $redirect = null;
    public $durtion = 0;
    public $tokens = null;

    /**
     * @inheritdoc
     */
    public function execute($queue) {
        Yii::error('[JPushJob EXECUTE]', 'queue');
        if ($this->title == null || $this->tokens == null) {
            return false;
        }

        if ($this->tokens !== 'all' && (!is_array($this->tokens) || empty($this->tokens))) {
            return false;
        }

        $configs = [
            'category' => 'system',
            'extras' => [],
        ];
        if ($this->redirect != null) {
            $configs['extras'] = ['redirect' => $this->redirect];
        }

        $options = [];
        if ($this->durtion) {
            $options['big_push_duration'] = $this->durtion;
        }
        $status = $this->push($this->title, $this->tokens, $configs, $options);
        Yii::error('[PUSH Response]:' . \yii\helpers\VarDumper::export($status), 'queue');
        return true;
    }

    protected function push($title, $tokens, $configs, $options = []) {
        $sendOptions = ['apns_production' => true, 'big_push_duration' => 1];
        if (!empty($options)) {
            $sendOptions = ArrayHelper::merge($sendOptions, $options);
        }

        $jPushConfig = Yii::$app->params['jpush'];
        $client = new Client($jPushConfig['key'], $jPushConfig['secret']);
        $pusher = $client->push();

        $pusher->setPlatform(['ios', 'android'])
        ->setNotificationAlert($title)
        ->options($sendOptions)
        ->iosNotification($title, ArrayHelper::merge($configs, ['sound' => 'default']))
        ->androidNotification($title, $configs)
        ->message($title, ArrayHelper::merge($configs, ['content_type' => 'text']));

        if ($tokens == 'all') {
            $pusher->addAllAudience();
        } else {
            $pusher->addRegistrationId($tokens);
        }
        //发送
        return $pusher->send();
    }

}
